import Vue from 'vue'
import VueRouter from 'vue-router'
// 在js文件中用store,就得导入store
import store from '@/store'

Vue.use(VueRouter)
// 最大级别的组件会显示在App.vue中
const routes = [
  // 登录
  { path: '/login', component: () => import('@/views/Login.vue') },
  //  注册
  { path: '/reg', component: () => import('@/views/Reg.vue') },
  // 后台首页
  {
    path: '/',
    component: () => import('@/views/Home.vue'),
    children: [
      {
        path: 'home',
        component: () => import('@/views/Chart.vue')
      },
      {
        path: 'user-info',
        component: () => import('@/views/user/UserInfo.vue')
      },
      {
        path: 'user-avatar',
        component: () => import('@/views/user/UserAvatar.vue')
      },
      {
        path: 'user-pwd',
        component: () => import('@/views/user/RePwd.vue')
      },
      {
        path: 'art-cate',
        component: () => import('@/views/article/CateList.vue')
      },
      {
        path: 'art-list',
        component: () => import('@/views/article/ArtList.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 这里固定写全局导航守卫
router.beforeEach((to, from, next) => {
  // to.path即将要访问的路由地址是什么
  if (to.path === '/login' || to.path === '/reg') {
    // next()放行，next(false)不放行，next('/login')跳转到登录
    // 如果访问的是登录和注册就运行放行
    next()
  } else {
    // else说明访问的不是注册和登录，就要判断有没有token
    //  如果本地存储有token就放行
    if (store.state.user.token) {
      next()
    } else {
      // 否则跳转到登录
      next('/login')
    }
  }
})
export default router
